//
//  SearchPanel.m
//  AsyncImages
//
//  Created by Matthew on 12-2-8.
//  Copyright 2012年 develop4u.gr. All rights reserved.
//

#import "SearchPanel.h"
#import "ColorUtil.h"

#define WEB_SERVICE_1 @"http://photo.zhulong.com/mobile/ps.asp?name="
#define WEB_SERVICE_2 @"http://photo.zhulong.com/mobile/man.asp?name="
#define WEB_SERVICE_3 @"http://photo.zhulong.com/mobile/unit.asp?name="

#define DETAIL_SERVICE_1 @"http://photo.zhulong.com/mobile/detail.asp?id="
#define DETAIL_SERVICE_2 @"http://photo.zhulong.com/mobile/man_detail.asp?id="
#define DETAIL_SERVICE_3 @"http://photo.zhulong.com/mobile/unit_detail.asp?id="

#define PAGE_WIDTH 320
#define PAGE_HEIGHT 480

#define LEVEL_1_TABLE_HEIGHT 360
#define LEVEL_2_TABLE_HEIGHT 365

#define TABLE_OFFSET_Y 140

#define TABLE_ROW_HEIGHT 66

@implementation SearchPanel

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        search_type_id = 0;
        self.backgroundColor = [ColorUtil stringHexToUIColor:@"0xf0f0f0"];
        
        usedFlag1 = FALSE;
        usedFlag2 = FALSE;
        usedFlag3 = FALSE;
    }
    return self;
}

-(void) initWithTags:(NSArray *) inTagArr
              suffix:(NSString *) inSuffix
{
    UIColor *color = [ColorUtil stringHexToUIColor:@"0x112033"];//[UIColor redColor];
    
    UIView *topBgBar = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.frame.size.width, 45)];
    topBgBar.backgroundColor = color;
    [self addSubview:topBgBar];
    
    //init segment
    if (inTagArr != Nil && [inTagArr count]>0)
    {    
        seg = [[UISegmentedControl alloc] initWithItems:inTagArr];
        seg.frame = CGRectMake(35, 80, 250, 40);
        seg.selectedSegmentIndex = 0;
        search_type_id = 0;
        [seg addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:seg];
    }
    
    unit_trigger = [[NSString alloc] initWithFormat:@"unit_trigger_%@",inSuffix];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:unit_trigger object:Nil];
    
    searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(75,28,190, 30)];
    searchTextField.borderStyle = UITextBorderStyleRoundedRect;
    
    searchTextField.font = [UIFont systemFontOfSize:18.0];  //font size
    searchTextField.placeholder = @"输入搜索内容";  //place holder
    searchTextField.backgroundColor = [UIColor clearColor]; //background color
    searchTextField.autocorrectionType = UITextAutocorrectionTypeNo;	// no auto correction support
    
    searchTextField.keyboardType = UIKeyboardTypeDefault;  // type of the keyboard
    searchTextField.returnKeyType = UIReturnKeyDone;  // type of the return key
    
    searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;	// has a clear 'x' button to the right
    
    searchTextField.delegate = self;	// let us be the delegate so we know when the keyboard's "Done" button is pressed
    [self addSubview:searchTextField];
    
    table1 = [[XMLTable alloc] initWithFrame:CGRectMake(0,TABLE_OFFSET_Y, 
                                                        PAGE_WIDTH,LEVEL_1_TABLE_HEIGHT)];
    [table1 configTable:PAGE_WIDTH
            tableHeight:LEVEL_1_TABLE_HEIGHT
             tableWidth:TABLE_ROW_HEIGHT
         tableUnitStyle:1];    
    table1.suffix = inSuffix;
    [table1 configMsg];
    [table1 setAtomData:@"/feed/tag"
                   atom:@"tag"
                   feed:@"feed"];
    //[table1 triggerByURL:inTable1URL useFeatureImg:FALSE];
    [self addSubview:table1];
    
    table2 = [[XMLTable alloc] initWithFrame:CGRectMake(0,TABLE_OFFSET_Y, 
                                                        PAGE_WIDTH,LEVEL_1_TABLE_HEIGHT)];
    [table2 configTable:PAGE_WIDTH
            tableHeight:LEVEL_1_TABLE_HEIGHT
             tableWidth:TABLE_ROW_HEIGHT
         tableUnitStyle:1];
    table2.suffix = inSuffix;
    table2.hidden = TRUE;
    [table2 configMsg];
    [table2 setAtomData:@"/mans/man"
                   atom:@"man"
                   feed:@"mans"];
    //[table2 triggerByURL:inTable2URL useFeatureImg:FALSE];
    [self addSubview:table2];
    
    table3 = [[XMLTable alloc] initWithFrame:CGRectMake(0,TABLE_OFFSET_Y, 
                                                        PAGE_WIDTH,LEVEL_1_TABLE_HEIGHT)];
    [table3 configTable:PAGE_WIDTH
            tableHeight:LEVEL_1_TABLE_HEIGHT
             tableWidth:TABLE_ROW_HEIGHT
         tableUnitStyle:1];
    table3.suffix = inSuffix;
    table3.hidden = TRUE;
    [table3 configMsg];
    [table3 setAtomData:@"/feed/unit"
                   atom:@"unit"
                   feed:@"feed"];
    //[table3 triggerByURL:intable3URL useFeatureImg:FALSE];
    [self addSubview:table3];
    
    returnButton = [[ImageUIButton alloc] initWithFrame:CGRectMake(10,27, 55, 30)];
    [returnButton setImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    [returnButton setImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateSelected];
    [returnButton  addTarget:self action:@selector(mouseDownProc:) forControlEvents:UIControlEventTouchDown];
    returnButton.button_id = 10;
    [self addSubview:returnButton];
    
    searchButton = [[ImageUIButton alloc] initWithFrame:CGRectMake(280,27, 30, 31)];
    [searchButton setImage:[UIImage imageNamed:@"search_button.png"] forState:UIControlStateNormal];
    [searchButton setImage:[UIImage imageNamed:@"search_button.png"] forState:UIControlStateSelected];
    [searchButton  addTarget:self action:@selector(mouseDownProc:) forControlEvents:UIControlEventTouchDown];
    searchButton.button_id = 11;
    [self addSubview:searchButton];
    
    detailPanel  = [[BaseDetailPanel alloc] initWithFrame:CGRectMake(PAGE_WIDTH, 0, PAGE_WIDTH, PAGE_HEIGHT)];
    detailPanel.theDetailPageHeight = 440;
    [detailPanel trigger:DETAIL_SERVICE_1
            infoBarTitle: @""
                  suffix:@"search_detail_panel"];
    [self addSubview:detailPanel];
    
    detail_view_exit = @"detail_view_exit_search_detail_panel";//[[NSString alloc] initWithFormat:@"detail_view_exit_%@",@"search_detail_panel"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSelector:) name:detail_view_exit object:Nil];
    
}

- (void)segmentAction:(UISegmentedControl*)sender 
{
    table1.hidden = TRUE;
    table2.hidden = TRUE;
    table3.hidden = TRUE;
    
    switch (sender.selectedSegmentIndex) 
    {
        case 0:
            table1.hidden = FALSE;
            search_type_id = 0;
            break;
        case 1:
            table2.hidden = FALSE;
            search_type_id = 1;
            break;
        case 2:
            table3.hidden = FALSE;
            search_type_id = 2;
            break;
        default:
            break;
    }
    
    //search_type_id
    if (sender.selectedSegmentIndex >=0 && sender.selectedSegmentIndex <= 2) 
    {
        search_type_id = sender.selectedSegmentIndex;
    }
    
}

-(void) mouseDownProc:(id)sender
{
    ImageUIButton *button = sender;
    
    if (button.button_id == 10) //back
    {
        [UIView transitionWithView:self  duration:0.4f 
                           options:UIViewAnimationCurveEaseOut  
                        animations:
         ^{
             self.transform = CGAffineTransformMakeTranslation(0,0);
         }
                        completion:NULL];

    }
    else if(button.button_id == 11)//refresh
    {
        NSLog(@"THE HIT TEXT %@",searchTextField.text);
        
        //[[NSNotificationCenter defaultCenter] postNotificationName:page_refresh object:self];
    }
}

-(void) shiftIn
{
    [UIView transitionWithView:self  duration:0.4f 
                       options:UIViewAnimationCurveEaseOut  
                    animations:
     ^{
         self.transform = CGAffineTransformMakeTranslation(-PAGE_WIDTH,0);
     }
                    completion:NULL];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self doSearchAction:textField.text];
    [textField resignFirstResponder];
    return YES;
}

-(void) doSearchAction:(NSString *) inQuery
{
    //UTF-8 SOLUTION
    NSString *utf8QueryStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                                                                                   NULL,
                                                                                   (CFStringRef)inQuery,
                                                                                   NULL,
                                                                                   (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                   kCFStringEncodingUTF8 );

    if (search_type_id == 0) 
    {
        NSString *theUrl = [[NSString alloc] initWithFormat:@"%@%@",WEB_SERVICE_1,utf8QueryStr];
        if (!usedFlag1) 
        {
            usedFlag1 = TRUE;
            [table1 triggerByURL:theUrl useFeatureImg:FALSE];
        }
        else
        {
            table1.xmlPath = theUrl;
            [table1 refresh];
        }
    }
    else if (search_type_id == 1) 
    {
        NSString *theUrl = [[NSString alloc] initWithFormat:@"%@%@",WEB_SERVICE_2,utf8QueryStr];
        if (!usedFlag2) 
        {
            usedFlag2 = TRUE;
            [table2 triggerByURL:theUrl useFeatureImg:FALSE];
        }
        else
        {
            table2.xmlPath = theUrl;
            [table2 refresh];
        }
    }
    else if (search_type_id == 2) 
    {
        NSString *theUrl = [[NSString alloc] initWithFormat:@"%@%@",WEB_SERVICE_3,utf8QueryStr];
        if (!usedFlag3) 
        {
            usedFlag3 = TRUE;
            [table3 triggerByURL:theUrl useFeatureImg:FALSE];
        }
        else
        {
            table3.xmlPath = theUrl;
            [table3 refresh];
        }
    }
}

-(void) notificationSelector:(NSNotification *) notification
{
    NSString *curNotificationName = [notification name];
    
    if ([curNotificationName isEqualToString:unit_trigger])
    {
        MWFeedItem *tempAtom = [notification object];
        
        if (search_type_id == 0) 
        {
            [detailPanel setURLPrefixByURL:DETAIL_SERVICE_1];
        }
        else  if (search_type_id == 1) 
        {
            [detailPanel setURLPrefixByURL:DETAIL_SERVICE_2];
        }
        else  if (search_type_id == 2) 
        {
            [detailPanel setURLPrefixByURL:DETAIL_SERVICE_3];
        }
        
        NSLog(@"IDENTIFIER%@ TITLE%@",tempAtom.identifier,tempAtom.title);
        
        [detailPanel triggerByBuildId:tempAtom.identifier];
        [detailPanel setUpTitle:tempAtom.title];
        
        [UIView transitionWithView:self  duration:0.4f 
                           options:UIViewAnimationCurveEaseOut  
                        animations:
         ^{
             detailPanel.transform = CGAffineTransformMakeTranslation(-PAGE_WIDTH,0);
         }
                        completion:NULL];
    }
    else if([curNotificationName isEqualToString:detail_view_exit])
    {
        [UIView transitionWithView:detailPanel duration:0.4f 
                           options:UIViewAnimationCurveEaseOut  
                        animations:
         ^{
             detailPanel.transform = CGAffineTransformMakeTranslation(0,0);
             [table1 releaseSelectedNode];
             [table2 releaseSelectedNode];
             [table3 releaseSelectedNode];
         }
                        completion:NULL]; 
    }
}

- (void)dealloc
{
    [super dealloc];
}

@end
